//
//  USGridView.m
//  us
//
//  Created by karry on 2025/5/16.
//

#import "USGridView.h"

@implementation USGridView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    if (self = [super initWithCoder:coder]) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    _gridColor = [UIColor mi_3_color];
    _fillColor = [UIColor mi_1_color];
    _gridSpacing = 18;
    self.backgroundColor = [UIColor clearColor];
}

- (void)setGridColor:(UIColor *)gridColor {
    _gridColor = gridColor;
    [self setNeedsDisplay];
}

- (void)setFillColor:(UIColor *)fillColor {
    _fillColor = fillColor;
    [self setNeedsDisplay];
}

- (void)setGridSpacing:(CGFloat)gridSpacing {
    _gridSpacing = gridSpacing;
    [self setNeedsDisplay];
}

- (void)prepareForInterfaceBuilder {
    [super prepareForInterfaceBuilder];
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    if (!ctx) return;

    // 填充背景
    [self.fillColor setFill];
    CGContextFillRect(ctx, rect);

    // 设置网格颜色
    CGContextSetStrokeColorWithColor(ctx, self.gridColor.CGColor);
    CGContextSetLineWidth(ctx, 0.5);

    CGFloat spacing = self.gridSpacing;

    // 垂直线
    for (CGFloat x = 0; x <= CGRectGetWidth(rect); x += spacing) {
        CGContextMoveToPoint(ctx, x, 0);
        CGContextAddLineToPoint(ctx, x, CGRectGetHeight(rect));
    }

    // 水平线
    for (CGFloat y = 0; y <= CGRectGetHeight(rect); y += spacing) {
        CGContextMoveToPoint(ctx, 0, y);
        CGContextAddLineToPoint(ctx, CGRectGetWidth(rect), y);
    }

    CGContextStrokePath(ctx);
}

@end
